<template>
  <div>
    <template v-if="localData.type == 'checkbox'">
      <el-form-item label="显示全选">
        <el-switch v-model="localData.all" />
      </el-form-item>
    </template>
    <template v-if="['radio', 'checkbox'].includes(localData.type)">
      <el-form-item label="显示边框" v-if="!localData.button">
        <el-switch v-model="localData.border" />
      </el-form-item>
      <el-form-item label="按钮模式" v-if="!localData.border">
        <el-switch v-model="localData.button" />
      </el-form-item>
    </template>
    <!-- <el-form-item label="选项颜色">
      <el-switch v-model="localData.showDicColor" />
    </el-form-item> -->
    <el-form-item label="列表数据回显字典" label-width="140" v-if="localData.parentName">
      <el-switch v-model="localData.dictFromScope" />
    </el-form-item>
    <el-form-item label="回显数据字段" v-if="localData.dictFromScope">
      <el-input v-model="localData.dictFromScopeField" placeholder="请输入回显数据字段" />
    </el-form-item>
    <div
      class="el-form-item el-form-item--default el-form--label-top"
      v-if="!localData.dictFromScope"
    >
      <label class="el-form-item__label" style="padding: 0">字典配置：</label>
      <div class="el-form-item__content">
        <el-tabs v-model="localData.dicOption" stretch @tab-change="handleTabClick">
          <el-tab-pane label="静态数据" name="static">
            <draggable
              tag="ul"
              :list="localData.dicData"
              :group="{ name: 'dic' }"
              ghost-class="ghost"
              handle=".drag-item"
            >
              <template #item="{ element }">
                <li>
                  <el-icon
                    class="el-icon drag-item"
                    style="font-size: 16px; margin: 0 5px; cursor: move"
                  ><Operation
                  /></el-icon>
                  <!-- <i
                    class="drag-item el-icon-s-operation"
                    style="font-size: 16px; margin: 0 5px; cursor: move"
                  ></i> -->
                  <el-input
                    style="margin-right: 5px"
                    size="default"
                    clearable
                    v-model="element.label"
                    placeholder="label"
                  />
                  <el-input
                    :style="{
                      'margin-right':
                        localData.type == 'select' || localData.type == 'radio' ? '5px' : '0'
                    }"
                    size="default"
                    clearable
                    v-model="element.value"
                    placeholder="value"
                  />
                  <!-- <el-input
                  v-if="data.type == 'select' || data.type == 'radio'"
                  size="mini"
                  clearable
                  v-model="item.desc"
                  placeholder="隐藏字段"
                ></el-input> -->
                  <el-color-picker v-if="localData.showDicColor" v-model="element.color" />
                  <el-button
                    @click="handleRemoveFields(index)"
                    circle
                    plain
                    type="danger"
                    size="default"
                    icon="el-icon-minus"
                    style="padding: 4px; margin-left: 5px"
                  />
                </li>
              </template>
            </draggable>
            <div style="margin-left: 22px; display: flex; gap: 20px">
              <el-button link @click="handleAddFields(localData.dicData)">添加列 </el-button>
              <el-button link @click="batchAdd(localData.dicData)">批量编辑 </el-button>
              <option-ref
                v-if="localData.type !== 'checkbox'"
                :data="localData"
                :formJson="formJson"
              />
              <connect-more
                v-if="localData.type !== 'checkbox'"
                :data="localData"
                :notSavedOptions="notSavedOptions"
                :formJson="formJson"
              />
              <!-- <connect-more v-show="data.hasParent!='N'" :data="data" :notSavedOptions="notSavedOptions"/> -->
            </div>
          </el-tab-pane>

          <el-tab-pane label="字典配置" name="dictionary">
            值集筛选
            <el-select
              v-model="localData.dictionary"
              placeholder="值集筛选"
              size="default"
              @change="handleDictionaryChange"
              style="width: 100%"
            >
              <el-option
                v-for="item in optionsDictionary"
                :key="item.dictType"
                :label="item.dictName"
                :value="item.dictType"
              />
            </el-select>

            <div v-if="localData.dictionary">
              子选项
              <draggable
                tag="ul"
                :list="localData.dicData"
                :group="{ name: 'dic' }"
                ghost-class="ghost"
                handle=".drag-item"
              >
                <template #item="{ element }">
                  <li>
                    <el-icon
                      class="el-icon drag-item"
                      style="font-size: 16px; margin: 0 5px; cursor: move"
                    ><Operation
                    /></el-icon>
                    <!-- <i
                      class="drag-item el-icon-s-operation"
                      style="font-size: 16px; margin: 0 5px; cursor: move"
                    ></i> -->
                    <el-input
                      style="margin-right: 5px"
                      size="default"
                      clearable
                      v-model="element.label"
                      placeholder="label"
                    />
                    <el-input
                      :style="{
                        'margin-right':
                          localData.type == 'select' || localData.type == 'radio' ? '5px' : '0'
                      }"
                      size="default"
                      clearable
                      v-model="element.value"
                      placeholder="value"
                    />
                    <el-color-picker v-if="localData.showDicColor" v-model="element.color" />
                    <el-button
                      @click="handleRemoveFields(index)"
                      circle
                      plain
                      type="danger"
                      size="default"
                      icon="el-icon-minus"
                      style="padding: 4px; margin-left: 5px"
                    />
                  </li>
                </template>
              </draggable>
              <!-- 字典配置由于变为动态获取，暂时无法支持高级操作了 -->
              <!-- <div style="display: flex; gap: 20px">
                <option-ref
                  v-if="data.type !== 'checkbox'"
                  :data="data"
                  :formJson="formJson"
                />
                <connect-more
                  v-if="data.type !== 'checkbox'"
                  :data="data"
                  :notSavedOptions="notSavedOptions"
                />
              </div> -->
            </div>
          </el-tab-pane>
          <el-tab-pane label="远端数据" name="remote">
            <el-switch v-model="localData.chooseApi" active-text="选择api" inactive-text="自定义" />
            <api-selector v-if="localData.chooseApi" v-model="localData.formDataUrl" />
            <div v-else>
              网址
              <el-input
                v-if="localData.dicContentType == 'json'"
                v-model="localData.dicUrl"
                size="default"
                placeholder="远端数据字典网址"
              />
              <el-input
                v-else
                v-model="localData.formDataUrl"
                size="default"
                placeholder="远端数据字典网址"
              />
              <span v-if="localData.dicContentType == 'json'">
                远程搜索
                <el-switch v-model="localData.remote" />
              </span>

              <br />
              请求方法
              <el-select
                v-model="localData.dicMethod"
                placeholder="请求方法"
                size="default"
                style="width: 100%"
              >
                <el-option label="POST" value="post" />
                <el-option label="GET" value="get" />
              </el-select>
              <br />
              请求类型
              <el-select
                v-model="localData.dicContentType"
                placeholder="请求类型"
                size="default"
                style="width: 100%"
                @change="clearDicUrl"
              >
                <el-option label="formData" value="formData" />
                <el-option label="json" value="json" />
              </el-select>
            </div>
            <p>
              请求参数
              <avue-dynamic
                v-if="localData.dicQueryConfig"
                v-model="localData.dicQueryConfig"
                :children="option"
              />
            </p>
            <p v-if="localData.dicUrl || localData.formDataUrl">
              返回结构体层次
              <el-input v-model="localData.dicRes" placeholder="默认为res" />
            </p>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <div class="el-form-item el-form-item--default el-form--label-top">
      <label class="el-form-item__label" style="padding: 0">字典key配置：</label>
      <div class="el-form-item__content">
        <ul>
          <li v-for="(value, key) in localData.props" :key="key">
            <span style="width: 50px">{{ key }}</span>
            <el-input
              size="default"
              v-model="localData.props[key]"
              clearable
              placeholder="key配置"
            />
          </li>
        </ul>
      </div>
    </div>
    <el-form-item
      v-if="localData.dicOption == 'remote' && localData.dicContentType == 'json'"
      label="重新请求字典(crud)"
      label-width="150px"
    >
      <el-switch v-model="localData.dicFlag" />
    </el-form-item>
    <template v-if="localData.type == 'select'">
      <el-form-item label="默认选中第一条" label-width="120px">
        <el-switch v-model="localData.selectFirst" />
      </el-form-item>
      <el-form-item label="是否多选">
        <el-switch v-model="localData.multiple" />
      </el-form-item>
      <el-form-item label="是否可拖拽" label-width="110px" v-if="localData.multiple">
        <template #label>
          <el-link
            :underline="false"
            href="https://avuejs.com/form/form-select.html#%E6%8B%96%E6%8B%BD"
            target="_blank"
          >是否可拖拽
            <el-icon><QuestionFilled /></el-icon>
            <!-- <i class="el-icon-question"></i
          > -->
          </el-link>
        </template>
        <el-switch v-model="localData.drag" />
      </el-form-item>
      <el-form-item label="多选数量限制" label-width="110px" v-if="localData.multiple">
        <el-input-number
          v-model="localData.limit"
          controls-position="right"
          placeholder="多选限制"
          :min="0"
          :max="localData.dicData.length"
        />
      </el-form-item>

      <div class="el-form-item el-form-item--default el-form--label-top">
        <label class="el-form-item__label" style="padding: 0">级联配置：</label>
        <div class="el-form-item__content">
          <draggable
            tag="ul"
            :list="localData.cascaderItem || localData.cascader"
            :group="{ name: 'cascaderItem' }"
            ghost-class="ghost"
            handle=".drag-item"
          >
            <template #item="{ index }">
              <li>
                <el-icon
                  class="el-icon drag-item"
                  style="font-size: 16px; margin: 0 5px; cursor: move"
                ><Operation
                /></el-icon>
                <!-- <i
                  class="drag-item el-icon-s-operation"
                  style="font-size: 16px; margin: 0 5px; cursor: move"
                ></i> -->
                <el-input
                  v-if="avueVersion('2.9.0')"
                  size="default"
                  v-model="localData.cascaderItem[index]"
                  clearable
                  placeholder="级联属性值"
                />
                <el-input
                  v-else
                  size="default"
                  v-model="localData.cascader[index]"
                  clearable
                  placeholder="级联属性值"
                />
                <el-button
                  @click="handleRemoveCascaderItemFields(index)"
                  circle
                  plain
                  type="danger"
                  size="default"
                  icon="el-icon-minus"
                  style="padding: 4px; margin-left: 5px"
                />
              </li>
            </template>
          </draggable>
          <div style="margin-left: 22px">
            <el-button link @click="handleAddCascaderItemFields">添加列 </el-button>
          </div>
        </div>
      </div>
      <el-form-item
        v-if="
          (localData.cascaderItem || localData.cascader) &&
            (localData.cascaderItem || localData.cascader).length > 0
        "
        label="级联默认选中"
        label-width="110px"
      >
        <el-input-number
          v-model="localData.cascaderIndex"
          controls-position="right"
          placeholder="级联默认选中"
          :min="0"
        />
      </el-form-item>
      <el-form-item label="是否可清空" label-width="110px">
        <el-switch v-model="localData.clearable" />
      </el-form-item>
      <el-form-item label="是否可搜索" label-width="110px">
        <el-switch v-model="localData.filterable" />
      </el-form-item>
    </template>
    <el-form-item label="尺寸" v-if="localData.border || localData.button">
      <el-radio-group v-model="localData.size" size="default">
        <el-radio-button label="large">正常</el-radio-button>
        <el-radio-button label="default">小</el-radio-button>
        <el-radio-button label="small">超小</el-radio-button>
      </el-radio-group>
    </el-form-item>
    <!-- <data-contact :data='data'></data-contact> -->
    <batch-add
      v-model:showDialog="showDialog"
      v-model:data="localData"
      @close="showDialog = false"
      :oldDiceStr="oldDiceStr"
    />
  </div>
</template>

<script>
import Draggable from 'vuedraggable'
// import MonacoEditor from "./../utils2/monaco-editor";
import { searchAll } from '@base/api/base/dict/type'
import batchAdd from '../../components/batchAddFile.vue'
import { buildExtColNames } from '@/utils/zmids'
import OptionRef from '../../components/optionRef.vue'
import connectMore from '../../components/connectMore.vue'

// 默认的选项颜色
const COLORS = [
  'rgb(235, 80, 80)',
  'rgb(240, 168, 0)',
  'rgb(70, 194, 111)',
  'rgb(162, 194, 4)',
  'rgb(0, 174, 209)',
  'rgb(88, 101, 245)',
  'rgb(198, 67, 224)'
]

export default {
  name: 'ConfigSelect',
  components: { Draggable, batchAdd, OptionRef, connectMore },
  props: {
    data: {
      type: Object,
      default: () => {}
    },
    notSavedOptions: {
      type: Array,
      default: () => []
    },
    formJson: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      showDialog: false,
      optionsDictionary: [],
      childDictionary: [],
      option: {
        column: [
          {
            type: 'input',
            prop: 'key',
            label: 'key'
          },
          {
            type: 'input',
            prop: 'value',
            label: 'value'
          }
        ]
      },
      options: {
        fullScreen: true,
        minimap: {
          enabled: false
        }
      },
      dicFormatter: '',
      oldDiceStr: '',
      preTab: '', // 用于记录上一个tab
      localData: {}
    }
  },

  watch: {
    data: {
      handler(newVal) {
        if (newVal) {
          this.localData = newVal
        }
      },
      deep: true,
      immediate: true
    },
    localData: {
      handler(newVal) {
        this.$emit('update:data', newVal)
      },
      deep: true
    },
    'localData.prop': {
      handler() {
        if (this.localData.type == 'select' && !this.localData.props) {
          this.localData.props = { label: 'label', value: 'value' }
          // this.$set(this.localData, 'props', { label: 'label', value: 'value' })
        }
        if (!this.avueVersion('2.9.0') && this.localData.cascaderItem) {
          this.localData.cascader = this.localData.cascaderItem
          // this.$set(this.localData, 'cascader', this.localData.cascaderItem)\
          delete this.localData.cascaderItem
          // this.$delete(this.localData, 'cascaderItem')
        }
        const { dicFormatter } = this.localData
        this.dicFormatter = dicFormatter
          ? dicFormatter + ''
          : '(res) => {\r\n  return res.data\r\n}'
      },
      immediate: true
    },
    'localData.multiple'(newVal) {
      if (newVal !== undefined) {
        if (newVal) {
          this.localData.valueType = 'array'
          // this.$set(this.localData, 'valueType', 'array')
        } else {
          this.localData.valueType = 'string'
          // this.$set(this.localData, 'valueType', 'string')
        }
      }
    },
    dicFormatter: {
      handler(val) {
        try {
          this.localData.dicFormatter = eval(val)
        } catch (e) {
          // console.error(e)
        }
      }
    }
  },
  created() {
    this.getDictionary()
  },
  methods: {
    handleDictionaryChange(e) {
      // console.log(e);
      this.getDicts(e).then((response) => {
        response.data.map((item, index) => {
          item.value = item.dictValue
          item.label = item.dictLabel
          item.color = this.getColorByIdx(index)
          item.desc = ''
          item.connectChild = [
            {
              childValue: [],
              childdataList: [],
              childprop: ''
            }
          ]
        })
        this.localData.dicData = response.data
        // this.$set(this.localData, 'dicData', response.data)
        // this.childDictionary = response.data;
      })
    },
    getDictionary() {
      let params = {
        orderBy: 'UPDATE_TIME',
        sortDirect: 'DESC'
      }
      searchAll(params).then((res) => {
        this.optionsDictionary = res.data
      })
    },
    handleRemoveFields(index) {
      this.localData.dicData.splice(index, 1)
    },
    batchAdd(data) {
      console.log(data)
      let oldDice = []
      data.forEach((element) => {
        oldDice.push(element.label)
      })
      this.oldDiceStr = oldDice.join('\n')

      this.showDialog = true
    },
    handleAddFields(data) {
      const i = data.length + 1
      const col = Number(data[data.length - 1].value) + 1
      if (!this.localData.dicData) {
        this.localData.dicData = [
          {
            label: `字段${i}`,
            value: `${col}`,
            color: this.getColorByIdx(i),
            compsRef: []
          }
        ]
        // this.$set(this.localData, 'dicData', [
        //   {
        //     label: `字段${i}`,
        //     value: `${col}`,
        //     color: this.getColorByIdx(i),
        //     compsRef: []
        //   }
        // ])
      } else {
        this.localData.dicData.push({
          label: `字段${i}`,
          value: `${col}`,
          color: this.getColorByIdx(i),
          compsRef: []
        })
      }
    },
    handleRemoveCascaderItemFields(index) {
      if (this.avueVersion('2.9.0')) this.localData.cascaderItem.splice(index, 1)
      else this.localData.cascader.splice(index, 1)
    },
    handleAddCascaderItemFields() {
      if (this.avueVersion('2.9.0')) {
        if (!this.localData.cascaderItem) {
          this.localData.cascaderItem = []
          // this.$set(this.localData, 'cascaderItem', [])
        }
        this.localData.cascaderItem.push('')
      } else {
        if (!this.localData.cascader) {
          this.localData.cascader = []
          // this.$set(this.localData, 'cascader', [])
          delete this.localData.cascaderItem
        }
        this.localData.cascader.push('')
      }
    },
    handleTabClick(name) {
      // console.log("name", instance, oldName);
      // const { name } = instance
      if (name == this.preTab) {
        return
      }

      this.preTab = name

      this.resetSelectSetting()

      if (name == 'remote') {
        this.localData.dicRes = 'res.data'
        this.localData.dicContentType = 'formData'
        this.localData.dicMethod = 'post'
        // this.$set(this.localData, 'dicRes', 'res.data')
        // this.$set(this.localData, 'dicContentType', 'formData')
        // this.$set(this.localData, 'dicMethod', 'post')
      }

      // if (!this.localData.props) {
      //   this.$set(this.localData, "props", { label: "label", value: "value" });
      // }
      if (name == 'static') {
        this.localData.dicData = [
          {
            label: '选项一',
            value: '0',
            color: this.getColorByIdx(0),
            connectChild: [
              {
                childValue: [],
                childdataList: [],
                childprop: ''
              }
            ]
          },
          {
            label: '选项二',
            value: '1',
            color: this.getColorByIdx(1),
            connectChild: [
              {
                childValue: [],
                childdataList: [],
                childprop: ''
              }
            ]
          },
          {
            label: '选项三',
            value: '2',
            color: this.getColorByIdx(2),
            connectChild: [
              {
                childValue: [],
                childdataList: [],
                childprop: ''
              }
            ]
          }
        ]
        // this.$set(this.localData, 'dicData', [
        //   {
        //     label: '选项一',
        //     value: '0',
        //     color: this.getColorByIdx(0),
        //     connectChild: [
        //       {
        //         childValue: [],
        //         childdataList: [],
        //         childprop: ''
        //       }
        //     ]
        //   },
        //   {
        //     label: '选项二',
        //     value: '1',
        //     color: this.getColorByIdx(1),
        //     connectChild: [
        //       {
        //         childValue: [],
        //         childdataList: [],
        //         childprop: ''
        //       }
        //     ]
        //   },
        //   {
        //     label: '选项三',
        //     value: '2',
        //     color: this.getColorByIdx(2),
        //     connectChild: [
        //       {
        //         childValue: [],
        //         childdataList: [],
        //         childprop: ''
        //       }
        //     ]
        //   }
        // ])
      } else if (name == 'dictionary') {
        this.localData.dictionary = undefined
        this.localData.props = {
          label: 'dictLabel',
          value: 'dictValue'
        }
        // this.$set(this.localData, 'dictionary', undefined)
        // this.$set(this.localData, 'props', {
        //   label: 'dictLabel',
        //   value: 'dictValue'
        // })
      }
    },
    // 切换tab时重置配置
    resetSelectSetting() {
      delete this.localData.dictionary
      delete this.localData.dicRes
      delete this.localData.dicUrl
      delete this.localData.formDataUrl
      delete this.localData.dicContentType
      this.localData.dicData = []
      this.localData.dicQueryConfig = []
      this.localData.props = {
        label: 'label',
        value: 'value',
        desc: 'desc'
      }
      // this.$set(this.localData, 'dicData', [])
      // this.$set(this.localData, 'dicQueryConfig', [])
      // this.$set(this.localData, 'props', {
      //   label: 'label',
      //   value: 'value',
      //   desc: 'desc'
      // })
    },
    getColorByIdx(index) {
      const num = Number(index)
      return COLORS[num % 7]
    },
    // 处理标签切换
    async handleTabLeave(name, oldName) {
      this.handleTabClick(name, oldName)
      // const str = "是否确认切换字典配置类型，切换后当前配置数据会被重置!";
      // return this.$confirm(str, "警告", {
      //   confirmButtonText: "确定",
      //   cancelButtonText: "取消",
      //   type: "warning",
      // })
      //   .then((res) => {
      //     // this.$set(this.localData,'dicOption',activeName)
      //     this.handleTabClick({ name });
      //     console.log("res", res);
      //   })
      //   .catch((e) => {
      //     console.log(e);
      //     reject();
      //   });
    },
    clearDicUrl() {
      this.localData.dicUrl = ''
      this.localData.formDataUrl = ''
      // this.$set(this.localData, 'dicUrl', '')
      // this.$set(this.localData, 'formDataUrl', '')
    }
  }
}
</script>

<style lang="scss" scoped>
:deep(.el-color-picker) {
  display: flex;
  align-items: center;

  .el-color-picker__trigger {
    width: 30px;
    height: 30px;
    border: 0;

    .el-color-picker__color {
      border-radius: 50%;

      .el-color-picker__color-inner {
        border-radius: 50%;
      }
    }

    .el-color-picker__icon {
      display: none;
    }
  }
}
</style>
